package com.loongtech.bi.manager.system;

import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.entity.system.EntityBiPlatform;
import com.loongtech.bi.entity.system.EntityBiServer;
import com.loongtech.bi.manager.realTime.BossRealTimeManager;
import com.loongtech.core.jpa.manager.ManagerQueryCacheBase;
import com.loongtech.core.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.AbstractMap.SimpleEntry;

@Service
public class BiPlatformManager extends ManagerQueryCacheBase<EntityBiPlatform> {
	private static final long serialVersionUID = 2L;
	
	@Autowired
	private BiServerManager biServerManager;
	@Autowired
	private BiChannelManager biChannelManager;

	public static List<EntityBiPlatform> PLATFORM_LIST;  // 平台全表
	public static List<EntityBiChannel> CHANNEL_LIST;  // 渠道全表
	public static List<EntityBiServer> SERVER_LIST;  // 区服全表
	public static Map<String, EntityBiPlatform> PLATFORM_MAP;  // 平台全表Map
	public static Map<String, EntityBiChannel> CHANNEL_MAP;  // 渠道全表Map
	public static Map<String, EntityBiServer> SERVER_MAP;  // 区服全表Map
	
	public static Map<String, List<EntityBiChannel>> PLATFORM_CHANNELS_MAP;  // 平台ID=渠道LIST
	public static Map<String, String> CHANNEL_PLATFORM_MAP;  // 渠道ID=平台ID
	public static Map<String, List<String>> CHANNEL_SERVERS_MAP;  // 渠道ID=区服IDLIST
	public static Map<String, List<String>> SERVER_CHANNELS_MAP;  // 区服ID=渠道IDLIST
	
	public void init() {
		PLATFORM_LIST = findByQuery("from EntityBiPlatform order by id");
		CHANNEL_LIST = biChannelManager.findByQuery("from EntityBiChannel order by id");
		SERVER_LIST = biServerManager.findByQuery("from EntityBiServer where used=true order by id");
		
		PLATFORM_MAP = new LinkedHashMap<>();
		for (EntityBiPlatform p : PLATFORM_LIST) {
			PLATFORM_MAP.put(p.getId(), p);
		}
		
		CHANNEL_MAP = new LinkedHashMap<>();
		PLATFORM_CHANNELS_MAP = new LinkedHashMap<>();
		CHANNEL_PLATFORM_MAP = new LinkedHashMap<>();
		for (EntityBiChannel c : CHANNEL_LIST) {
			CHANNEL_MAP.put(c.getId(), c);
			
			List<EntityBiChannel> cl = PLATFORM_CHANNELS_MAP.get(c.getPlatformId());
			if (cl == null) {
				cl = new ArrayList<>();
				PLATFORM_CHANNELS_MAP.put(c.getPlatformId(), cl);
			}
			cl.add(c);
			
			CHANNEL_PLATFORM_MAP.put(c.getId(), c.getPlatformId());
		}
		
		SERVER_MAP = new LinkedHashMap<>();
		CHANNEL_SERVERS_MAP = new LinkedHashMap<>();
		SERVER_CHANNELS_MAP = new LinkedHashMap<>();
		for (EntityBiServer s : SERVER_LIST) {
			SERVER_MAP.put(s.getId(), s);
			
			List<String> cls = new ArrayList<>();
			for (String c : s.getChannelIdList()) {
				cls.add(c);
				
				List<String> sls = CHANNEL_SERVERS_MAP.get(c);
				if (sls == null) {
					sls = new ArrayList<>();
					CHANNEL_SERVERS_MAP.put(c, sls);
				}
				sls.add(s.getId());
			}
			SERVER_CHANNELS_MAP.put(s.getId(), cls);
		}
	}
	
	/**
	 * 得到前num个新开的服的ID
	 * @param num
	 * @return
	 */
	public static List<EntityBiServer> getLastServerByNum(int num) {
		List<EntityBiServer> result = new ArrayList<>();
		
		for (int i = SERVER_LIST.size() - 1; i >= 0; i--) {
			if (result.size() < num) {
				result.add(SERVER_LIST.get(i));
			} else {
				break;
			}
		}
		
		return result;
	}
	
	/**
	 * 得到服务器容量
	 * @param serverid
	 * @return
	 */
	public static int getServerCapacityById(String serverid) {
		return (SERVER_MAP.get(serverid) == null || SERVER_MAP.get(serverid).getCapacity() == null) ? 0 : SERVER_MAP.get(serverid).getCapacity();
	}
	
	/**
	 * 根据平台ID取渠道列表，如果pid=0，则返回全列表
	 * @param pid
	 * @return
	 */
	public static List<EntityBiChannel> getChannelIdsByPlatformId(String pid) {
		List<EntityBiChannel> results = new ArrayList<>();
		if (!"0".equals(pid) && PLATFORM_CHANNELS_MAP.get(pid) != null) {
			results = PLATFORM_CHANNELS_MAP.get(pid);
		} else if ("0".equals(pid)) {
			results = CHANNEL_LIST;
		}
		
		Collections.sort(results, new EntityBiChannel().comparatorId);
		return results;
	}
	
	/**
	 * 根据平台ID和渠道ID取区服列表，如果pid=0且cid=0，则返回全列表
	 * @param pid
	 * @param cid
	 * @return
	 */
	public static List<EntityBiServer> getServerIdsByPlatAndChannId(String pid, String cid) {
		List<EntityBiServer> results = new ArrayList<>();
		
		if (!"0".equals(cid) && CHANNEL_SERVERS_MAP.get(cid) != null) {  // 选中了某个渠道且非空
			for (String s : CHANNEL_SERVERS_MAP.get(cid)) {
				if (SERVER_MAP.get(s) != null) {
					results.add(SERVER_MAP.get(s));
				}
			}
		} else {
			List<EntityBiChannel> cl = getChannelIdsByPlatformId(pid);
			for (EntityBiChannel c : cl) {
				List<String> sl = CHANNEL_SERVERS_MAP.get(c.getId());
				if (sl != null) {
					for (String s : sl) {
						if (SERVER_MAP.get(s) != null) {
							results.add(SERVER_MAP.get(s));
						}
					}
				}
			}
		}
		
		Collections.sort(results, new EntityBiServer().comparatorId);
		return results;
	}
	
	public static String getPlatformNameById(String platformId) {
		return "0".equals(platformId) ? "全平台" : (PLATFORM_MAP.get(platformId) == null ? platformId : PLATFORM_MAP.get(platformId).getName());
	}
	
	public static String getChannelNameById(String channelId) {
		return "0".equals(channelId) ? "全渠道" : (CHANNEL_MAP.get(channelId) == null ? channelId : CHANNEL_MAP.get(channelId).getName());
	}
	
	public static String getServerNameById(String serverId) {
		return "0".equals(serverId) ? "全区服" : (SERVER_MAP.get(serverId) == null ? serverId : SERVER_MAP.get(serverId).getName());
	}
	
	public static boolean isChannelBelong2Paltform(String platform, String channel) {
		if ("0".equals(platform) || "0".equals(channel)) {
			return true;
		}
		
		return platform.equals(CHANNEL_PLATFORM_MAP.get(channel));
	}
	
	public static boolean isServerBelong2Channel(String channel, String server) {
		if ("0".equals(channel) || "0".equals(server)) {
			return true;
		}
		
		return SERVER_CHANNELS_MAP.get(server).contains(channel);
	}
	
	public static boolean isChannelBelong2Server(String server, String channel) {
		if ("0".equals(server) || "0".equals(channel)) {
			return true;
		}
		
		return CHANNEL_SERVERS_MAP.get(channel).contains(server);
	}

    public static String getServerType(String serverid) {
        return (SERVER_MAP.get(serverid) == null || SERVER_MAP.get(serverid).getServerType() == null) ? BossRealTimeManager.HF_INDEX : SERVER_MAP.get(serverid).getServerType();
    }

    /**
     * 获取渠道表示和配置的auany platforms的map关系
     * @return map of Key=<channelId,platfromId> Val=set<platName>
     */
    public Map<Map.Entry<String, String>,Set<String>> getChanPlatSetMap() {
        Map<Map.Entry<String, String>,Set<String>> map = new HashMap<>();
        for(Map.Entry<String,EntityBiChannel> entry : CHANNEL_MAP.entrySet()){
            List<String> list = Utils.splitString(entry.getValue().getPlatName(),';');
            if(null == list || list.isEmpty()){
                continue;
            }
            Map.Entry<String, String> key = new SimpleEntry<String, String>(entry.getKey(),entry.getValue().getPlatformId());
            Set<String> set = map.get(key);
            if(null == set){
                set = new HashSet<>();
                map.put(key,set);
            }
            set.addAll(list);
        }
        return map;
    }

    /**
     * 查询
     */
    public List<EntityBiPlatform> searchByCriteria(EntityBiPlatform e) {
        List<Object> list = new ArrayList<>();
        StringBuilder hql = new StringBuilder(" from EntityBiPlatform e where 1=1 ");
        if (!Utils.isEmptyStr(e.getId())) {
            hql.append(" and e.id = ? ");
            list.add(e.getId());
        }
        if (!Utils.isEmptyStr(e.getDescription())) {
            hql.append(" and e.description like ?");
            list.add("%" + e.getDescription() + "%");
        }
        if (e.getGameId() != null) {
            hql.append(" and e.gameId like ?");
            list.add("%" + e.getGameId()+ "%");
        }
        if (!Utils.isEmptyStr(e.getName())) {
            hql.append(" and e.name like ?");
            list.add("%" + e.getName() + "%");
        }
        hql.append(" order by e.gameId,id");
        return findByQuery(hql.toString(), list.toArray());
    }
}
